/**
 *Copyright (c) 2024 watereyes
 * safetymanagement is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.purpose.service.impl;

import com.google.common.base.Splitter;
import com.koron.common.bean.DepartmentTreeBean;
import com.koron.common.bean.StaffBean;
import com.koron.common.domain.DataBean;
import com.koron.common.generator.DefaultIdGenerator;
import com.koron.common.web.Util;
import com.koron.purpose.bean.JobsDutiesBean;
import com.koron.purpose.bean.ResponsibilitiesLibBean;
import com.koron.purpose.domain.*;
import com.koron.purpose.mapper.*;
import com.koron.purpose.utils.BusinessCode;
import com.koron.risk.service.api.GridNodeService;
import com.koron.system.domain.DictData;
import com.koron.system.mapper.DictDataMapper;
import com.koron.system.service.api.DictDataService;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.koron.ebs.mybatis.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import org.swan.bean.MessageBean;

import java.io.InputStream;
import java.text.NumberFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class JobsDutiesServiceImpl implements com.koron.purpose.service.api.JobsDutiesService {
	private final static Logger logger= LoggerFactory.getLogger(JobsDutiesServiceImpl.class);

	@Autowired
	private DictDataService dataService;

	@Autowired
	private Util util;

	@Autowired
	private GridNodeService nodeService;

	@SuppressWarnings({ "deprecation", "rawtypes" })
	@Override
	public MessageBean<?> insert(JobsDutiesBean bean, StaffBean user) {
		MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
		Map checkMap = addCheck(bean);
		int code = (int) checkMap.get("code");
        String description = (String) checkMap.get("description");
        if(code != 0){
        	msg.setCode(code);
        	msg.setDescription(description);
        	return msg;
        }
		SessionFactory factory = new SessionFactory();
		try {
            JobsDutiesMapper mapper = factory.getMapper(JobsDutiesMapper.class);
            Integer count = mapper.addVerification(bean.getName(),bean.getCorpCode());
            if(count > 0){
            	factory.close(false);
    			msg.setCode(35002);
    			msg.setDescription("已存在相同名称岗位");
    			return msg;
            }
            bean.setAddTime(new Date());
			bean.setAddUser(user.getCode());
			bean.setAddUserName(user.getName());
			bean.setUpdateTime(new Date());
			bean.setUpdateUser(user.getCode());
			bean.setUpdateUserName(user.getName());
			bean.setId(DefaultIdGenerator.getInstance().generateLongId());
			//定人定岗
			List<JobsDutiesTask> taskList = bean.getTaskList();
			for (JobsDutiesTask task : taskList) {
				task.setId(DefaultIdGenerator.getInstance().generateLongId());
				task.setDutiesId(bean.getId());
			}
			//证照要求
			List<JobsDutiesCertificate> certificateList = bean.getCertificateList();
			for (JobsDutiesCertificate certificate : certificateList) {
				certificate.setId(DefaultIdGenerator.getInstance().generateLongId());
				certificate.setDutiesId(bean.getId());
			}
			//培训要求
			List<JobsDutiesTraining> trainingList = bean.getTrainingList();
			for (JobsDutiesTraining training : trainingList) {
				training.setId(DefaultIdGenerator.getInstance().generateLongId());
				training.setDutiesId(bean.getId());
			}
			//危害因素
			List<JobsDutiesHazard> hazardList = bean.getHazardList();
			for (JobsDutiesHazard hazard : hazardList) {
				hazard.setId(DefaultIdGenerator.getInstance().generateLongId());
				hazard.setDutiesId(bean.getId());
			}
            if(!taskList.isEmpty()){
            	factory.getMapper(JobsDutiesTaskMapper.class).batchInsert(taskList);
            }
            if(!certificateList.isEmpty()){
            	factory.getMapper(JobsDutiesCertificateMapper.class).batchInsert(certificateList);
            }
            if(!trainingList.isEmpty()){
            	factory.getMapper(JobsDutiesTrainingMapper.class).batchInsert(trainingList);
            }
            if(!hazardList.isEmpty()){
            	factory.getMapper(JobsDutiesHazardMapper.class).batchInsert(hazardList);
            }
			// 新增 岗位职责-职责项
			batchInsertRL(bean.getId(), bean.getResponsibilitiesLibIds(), factory);
			mapper.insert(bean);
			factory.close();
		} catch (Exception e) {
			factory.close(false);
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
			return msg;
		}
		return msg;
	}

	@SuppressWarnings({ "rawtypes", "deprecation" })
	@Override
	public MessageBean<?> update(JobsDutiesBean bean, StaffBean user) {
		MessageBean<?> msg = MessageBean.create(0, "SUCCESS", void.class);
		Map checkMap = addCheck(bean);
		int code = (int) checkMap.get("code");
        String description = (String) checkMap.get("description");
        if(code != 0){
        	msg.setCode(code);
        	msg.setDescription(description);
        	return msg;
        }
        if(StringUtils.isEmpty(bean.getId())){
			msg.setCode(35002);
			msg.setDescription("参数校验异常");
			return msg;
        }
        if(queryById(bean.getId()) == null){
        	msg.setCode(35002);
			msg.setDescription("参数校验异常");
			return msg;
        }
		SessionFactory factory = new SessionFactory();
		try {
            JobsDutiesMapper mapper = factory.getMapper(JobsDutiesMapper.class);
            Integer count = mapper.updateVerification(bean.getName(),bean.getCorpCode(),bean.getId());
            if(count > 0){
            	factory.close(false);
    			msg.setCode(35002);
    			msg.setDescription("已存在相同名称岗位");
    			return msg;
            }
			bean.setUpdateTime(new Date());
			bean.setUpdateUser(user.getCode());
			bean.setUpdateUserName(user.getName());
			//定人定岗
			List<JobsDutiesTask> taskList = bean.getTaskList();
			for (JobsDutiesTask task : taskList) {
				task.setId(DefaultIdGenerator.getInstance().generateLongId());
				task.setDutiesId(bean.getId());
			}
			//证照要求
			List<JobsDutiesCertificate> certificateList = bean.getCertificateList();
			for (JobsDutiesCertificate certificate : certificateList) {
				certificate.setId(DefaultIdGenerator.getInstance().generateLongId());
				certificate.setDutiesId(bean.getId());
			}
			//培训要求
			List<JobsDutiesTraining> trainingList = bean.getTrainingList();
			for (JobsDutiesTraining training : trainingList) {
				training.setId(DefaultIdGenerator.getInstance().generateLongId());
				training.setDutiesId(bean.getId());
			}
			//危害因素
			List<JobsDutiesHazard> hazardList = bean.getHazardList();
			for (JobsDutiesHazard hazard : hazardList) {
				hazard.setId(DefaultIdGenerator.getInstance().generateLongId());
				hazard.setDutiesId(bean.getId());
			}
			//删除子表数据
			factory.getMapper(JobsDutiesTaskMapper.class).delete(bean.getId());
			factory.getMapper(JobsDutiesCertificateMapper.class).delete(bean.getId());
			factory.getMapper(JobsDutiesTrainingMapper.class).delete(bean.getId());
			factory.getMapper(JobsDutiesHazardMapper.class).delete(bean.getId());

            if(!taskList.isEmpty()){
            	factory.getMapper(JobsDutiesTaskMapper.class).batchInsert(taskList);
            }
            if(!certificateList.isEmpty()){
            	factory.getMapper(JobsDutiesCertificateMapper.class).batchInsert(certificateList);
            }
            if(!trainingList.isEmpty()){
            	factory.getMapper(JobsDutiesTrainingMapper.class).batchInsert(trainingList);
            }
            if(!hazardList.isEmpty()){
            	factory.getMapper(JobsDutiesHazardMapper.class).batchInsert(hazardList);
            }
			// 根据 岗位职责id 删除 岗位职责-职责项
			factory.getMapper(JobsDutiesMapper.class).deleteRLByDutiesId(bean.getId());
			// 新增 岗位职责-职责项
			batchInsertRL(bean.getId(), bean.getResponsibilitiesLibIds(), factory);
			mapper.update(bean);
			factory.close();
		} catch (Exception e) {
			factory.close(false);
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
			return msg;
		}
		return msg;
	}

	@SuppressWarnings("deprecation")
	@Override
	public MessageBean<?> delete(String id) {
		MessageBean<?> msg = MessageBean.create(0, "success", void.class);
		JobsDutiesBean bean = queryById(id);
		if(bean == null){
			msg.setCode(35002);
			msg.setDescription("参数校验异常");
			return msg;
		}
		SessionFactory factory = new SessionFactory();
		try{
			factory.getMapper(JobsDutiesMapper.class).delete(id);
			factory.getMapper(JobsDutiesTaskMapper.class).delete(id);
			factory.getMapper(JobsDutiesCertificateMapper.class).delete(id);
			factory.getMapper(JobsDutiesTrainingMapper.class).delete(id);
			factory.getMapper(JobsDutiesHazardMapper.class).delete(id);
			// 根据 岗位职责id 删除 岗位职责-职责项
			factory.getMapper(JobsDutiesMapper.class).deleteRLByDutiesId(id);
			factory.close();
		} catch (Exception e) {
			factory.close(false);
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
		}
		return msg;
	}

	@Override
	public MessageBean<?> details(String id) {
		MessageBean<JobsDutiesBean> msg = MessageBean.create(0, "success", JobsDutiesBean.class);
		JobsDutiesBean bean = queryById(id);
		msg.setData(bean);
		return msg;
	}

	@SuppressWarnings({ "rawtypes", "deprecation", "unchecked" })
	@Override
	public MessageBean<?> list(String name, String corpCode, Integer page, Integer pageSize) {
		MessageBean<DataBean> msg= MessageBean.create(0,"SUCCESS", DataBean.class);
		if(StringUtils.isEmpty(corpCode)){
			msg.setCode(35002);
			msg.setDescription("参数校验异常");
			return msg;
		}
		Integer totalPage = null;
	    Integer totalNumber = null;
	    Integer start = null;
	    Integer end = null;
	    if (null!=page && pageSize!=null){
            if (page >0 && pageSize > 0){
            }else{
            	//第一页 10条数据
            	page =1;
            	pageSize=10;
            }
            start=(page<=1)?0:(page-1)*pageSize;
            end = pageSize;
        }
	    if(name != null){
	    	name = "%" + name +"%";
	    }else{
	    	name = "%%";
	    }

		List<String> codeList=new ArrayList<>();
	    codeList.add(corpCode);
	    try(SessionFactory factory = new SessionFactory();){
	    	totalNumber = factory.getMapper(JobsDutiesMapper.class).count(name,null,codeList);
	    	if(start != null && end != null){
				totalPage = (totalNumber+pageSize-1)/pageSize;
			}else{
				totalPage = 1;
				page = totalPage;
				pageSize = totalNumber;
			}
	    	DataBean data = new DataBean();
			data.setList(queryList(name,corpCode,null,start,end));
			data.setPageNo(page);
			data.setPageSize(pageSize);
			data.setTotalNumber(totalNumber);
			data.setTotalPage(totalPage);
			msg.setData(data);
	    } catch (Exception e) {
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
			return msg;
		}
		return msg;
	}

	@SuppressWarnings({ "rawtypes", "deprecation", "unchecked" })
	@Override
	public MessageBean<?> querySelectDate(String name, String corpCode, Integer page, Integer pageSize) {
		MessageBean<DataBean> msg= MessageBean.create(0,"SUCCESS", DataBean.class);

		List<String> codeList=new ArrayList<>();
		if(StringUtils.isEmpty(corpCode)||"776B361BFFAC4F00BBF459CD1303A8B2".equals(corpCode)){
			//默认集团code
			corpCode="776B361BFFAC4F00BBF459CD1303A8B2";
			codeList.add(corpCode);
		}else{
			//判断是八大下属公司哪家
			List<DepartmentTreeBean> departmentTreeBeanList= (List<DepartmentTreeBean>) util.depttree("776B361BFFAC4F00BBF459CD1303A8B2",0).getData();
			List<String> corpCodeList=departmentTreeBeanList.stream().map(DepartmentTreeBean::getDepartmentCode).collect(Collectors.toList());
			//排除下属单位离职退休单位
			if(corpCodeList.contains("02F871FD1F1041C0B27822297EF4D557")){
				corpCodeList.remove("02F871FD1F1041C0B27822297EF4D557");
			}
			if(!corpCodeList.contains(corpCode)){
				//是8个下属公司的下属部门
				//找上级单位
				List<DepartmentTreeBean> departmentTreeBeans= (List<DepartmentTreeBean>) util.getParentDepts(corpCode).getData();
				if(null!=departmentTreeBeans&&departmentTreeBeans.size()>0){
					//corpCode=departmentTreeBeans.get(1).getDepartmentCode();
					codeList=departmentTreeBeans.stream().map(DepartmentTreeBean::getDepartmentCode).collect(Collectors.toList());
					codeList.remove("776B361BFFAC4F00BBF459CD1303A8B2");
				}else{
					codeList.add("776B361BFFAC4F00BBF459CD1303A8B2");
				}
			}else{
				codeList.add(corpCode);
			}
		}
		Integer totalPage = null;
		Integer totalNumber = null;
		Integer start = null;
		Integer end = null;
		if (null!=page && pageSize!=null){
			if (page >0 && pageSize > 0){
			}else{
				//第一页 10条数据
				page =1;
				pageSize=10;
			}
			start=(page<=1)?0:(page-1)*pageSize;
			end = pageSize;
		}
		if(!StringUtils.isEmpty(name)){
			name = "%" + name +"%";
		}
		try(SessionFactory factory = new SessionFactory();){
			totalNumber = factory.getMapper(JobsDutiesMapper.class).count(name,null,codeList);
			if(start != null && end != null){
				totalPage = (totalNumber+pageSize-1)/pageSize;
			}else{
				totalPage = 1;
				page = totalPage;
				pageSize = totalNumber;
			}
			DataBean data = new DataBean();
			data.setList(factory.getMapper(JobsDutiesMapper.class).list(name,codeList,null,start, end));
			data.setPageNo(page);
			data.setPageSize(pageSize);
			data.setTotalNumber(totalNumber);
			data.setTotalPage(totalPage);
			msg.setData(data);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
			return msg;
		}
		return msg;
	}


	@SuppressWarnings({ "deprecation", "rawtypes", "unchecked" })
	@Override
	public MessageBean<?> positionList(String name, String corpCode, Integer page, Integer pageSize) {
		MessageBean<DataBean> msg= MessageBean.create(0,"SUCCESS", DataBean.class);
		if(StringUtils.isEmpty(corpCode)){
			msg.setCode(35002);
			msg.setDescription("参数校验异常");
			return msg;
		}
		Integer totalPage = null;
	    Integer totalNumber = null;
	    Integer start = null;
	    Integer end = null;
	    if (null!=page && pageSize!=null){
            if (page >0 && pageSize > 0){
            }else{
            	//第一页 10条数据
            	page =1;
            	pageSize=10;
            }
            start=(page<=1)?0:(page-1)*pageSize;
            end = pageSize;
        }
		if(!StringUtils.isEmpty(name)){
			name = "%" + name +"%";
		}
		List<String> codeList=new ArrayList<>();
		codeList.add(corpCode);
	    try(SessionFactory factory = new SessionFactory();){
	    	totalNumber = factory.getMapper(JobsDutiesMapper.class).count(name,null,codeList);
	    	if(start != null && end != null){
				totalPage = (totalNumber+pageSize-1)/pageSize;
			}else{
				totalPage = 1;
				page = totalPage;
				pageSize = totalNumber;
			}
	    	List<JobsDutiesBean> list = new ArrayList<>();
	    	list = factory.getMapper(JobsDutiesMapper.class).list(name,codeList,null,start,end);
	    	if(list.isEmpty()){
				return msg;
			}
			for (JobsDutiesBean bean : list) {
				bean.setTaskList(factory.getMapper(JobsDutiesTaskMapper.class).queryByTid(bean.getId()));
			}
	    	DataBean data = new DataBean();
			data.setList(list);
			data.setPageNo(page);
			data.setPageSize(pageSize);
			data.setTotalNumber(totalNumber);
			data.setTotalPage(totalPage);
			msg.setData(data);
	    } catch (Exception e) {
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
			return msg;
		}
		return msg;
	}

	@SuppressWarnings({ "unchecked", "rawtypes", "deprecation" })
	@Override
	public MessageBean<?> hazardMatrix(String corpCode, String name, Integer page, Integer pageSize) {
		MessageBean<Map> msg= MessageBean.create(0,"SUCCESS", Map.class);
		if(StringUtils.isEmpty(corpCode)){
			msg.setCode(35002);
			msg.setDescription("参数校验异常");
			return msg;
		}
		Integer totalPage = null;
	    Integer totalNumber = null;
	    Integer start = null;
	    Integer end = null;
	    if (null!=page && pageSize!=null){
            if (page >0 && pageSize > 0){
            }else{
            	//第一页 10条数据
            	page =1;
            	pageSize=10;
            }
            start=(page<=1)?0:(page-1)*pageSize;
            end = pageSize;
        }
	    if(!StringUtils.isEmpty(name)){
	    	name = "%"+name+"%";
	    }
	    List<String> codeList=new ArrayList<>();
		codeList.add(corpCode);
		try(SessionFactory factory = new SessionFactory();){
			totalNumber = factory.getMapper(JobsDutiesMapper.class).count(name,null,codeList);
	    	if(start != null && end != null){
				totalPage = (totalNumber+pageSize-1)/pageSize;
			}else{
				totalPage = 1;
				page = totalPage;
				pageSize = totalNumber;
			}
	    	Map retMap = new HashMap<>();
			retMap.put("totalPage", totalPage);
			retMap.put("totalNumber", totalNumber);
			retMap.put("pageNo", page);
			retMap.put("pageSize", pageSize);

	    	List<String> noteList = factory.getMapper(JobsDutiesHazardMapper.class).queryAllNote();
	    	List<JobsDutiesBean> list = factory.getMapper(JobsDutiesMapper.class).list(name,codeList,null,start,end);
	    	if(noteList.isEmpty() && list.isEmpty()){
				retMap.put("list", new ArrayList());
				retMap.put("noteList", new ArrayList());
				msg.setData(retMap);
				return msg;
	    	}
	    	List<List<String>> retList = new ArrayList<>();
	    	List<String> jobIds = new ArrayList<>();
	    	if(noteList.isEmpty() && !list.isEmpty()){
	    		List<String> jobsName = list.stream().map(JobsDutiesBean::getName).collect(Collectors.toList());
	    		retList.add(jobsName);
	    		retMap.put("list",retList);
				retMap.put("noteList", new ArrayList());
				msg.setData(retMap);
				return msg;
	    	}
	    	if(!noteList.isEmpty() && list.isEmpty()){
	    		retMap.put("list",new ArrayList());
				retMap.put("noteList", noteList);
				msg.setData(retMap);
				return msg;
	    	}
	    	jobIds = list.stream().map(JobsDutiesBean::getId).collect(Collectors.toList());
	    	List<Map<String,Object>> result = factory.getMapper(JobsDutiesMapper.class).hazardMatrix(noteList, jobIds);
	    	for (Map<String, Object> map : result) {
	    		List jobsValue = new ArrayList<>();
	    		jobsValue.add(map.get("jobName"));
    			for (String note : noteList) {
    				jobsValue.add(map.get(note));
    			}
    			retList.add(jobsValue);
			}
	    	retMap.put("noteList", noteList);
	    	retMap.put("list", retList);
			msg.setData(retMap);
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
			return msg;
		}
		return msg;
	}

	@SuppressWarnings({ "deprecation", "rawtypes", "unchecked" })
	@Override
	public MessageBean<?> positionMatrix(String corpCode,Integer isleader, Integer page, Integer pageSize) {
		MessageBean<Map> msg= MessageBean.create(0,"SUCCESS", Map.class);
		if(StringUtils.isEmpty(corpCode)){
			msg.setCode(35002);
			msg.setDescription("参数校验异常");
			return msg;
		}
		Integer totalPage = null;
	    Integer totalNumber = null;
	    Integer start = null;
	    Integer end = null;
	    if (null!=page && pageSize!=null){
            if (page >0 && pageSize > 0){
            }else{
            	//第一页 10条数据
            	page =1;
            	pageSize=10;
            }
            start=(page<=1)?0:(page-1)*pageSize;
            end = pageSize;
        }
		List<String> codeList=new ArrayList<>();
		codeList.add(corpCode);
		try(SessionFactory factory = new SessionFactory();){
			totalNumber = factory.getMapper(JobsDutiesMapper.class).count(null,isleader,codeList);
	    	if(start != null && end != null){
				totalPage = (totalNumber+pageSize-1)/pageSize;
			}else{
				totalPage = 1;
				page = totalPage;
				pageSize = totalNumber;
			}
	    	Map retMap = new HashMap<>();
			retMap.put("totalPage", totalPage);
			retMap.put("totalNumber", totalNumber);
			retMap.put("pageNo", page);
			retMap.put("pageSize", pageSize);

	    	List<DictData> ddlist = factory.getMapper(DictDataMapper.class).queryAll(null,"TaskType", null, null);
	    	List<JobsDutiesBean> list = factory.getMapper(JobsDutiesMapper.class).list(null,codeList,isleader,start,end);
	    	if(ddlist.isEmpty()){
				retMap.put("list", list);
				retMap.put("ddNameList", new ArrayList());
				msg.setData(retMap);
				return msg;
	    	}
	    	for (JobsDutiesBean bean : list) {
				List<Map<String,Object>> ret = factory.getMapper(JobsDutiesMapper.class).positionMatrix(ddlist,bean.getId());
				bean.setMatrix(ret);
			}
	    	List<String> ddNameList = ddlist.stream().map(DictData::getDictLabel).collect(Collectors.toList());
			retMap.put("list", list);
			retMap.put("ddNameList", ddNameList);
			msg.setData(retMap);
		} catch (Exception e) {
			msg.setCode(35001);
			msg.setDescription("数据库连接异常");
			return msg;
		}
		return msg;
	}

	@SuppressWarnings("deprecation")
	public JobsDutiesBean queryById(String id){
		JobsDutiesBean bean;
		try(SessionFactory factory = new SessionFactory();){
			bean = factory.getMapper(JobsDutiesMapper.class).queryById(id);
			if(bean == null){
				return bean;
			}
			bean.setTaskList(factory.getMapper(JobsDutiesTaskMapper.class).queryByTid(id));
			bean.setCertificateList(factory.getMapper(JobsDutiesCertificateMapper.class).queryByTid(id));
			bean.setTrainingList(factory.getMapper(JobsDutiesTrainingMapper.class).queryByTid(id));
			bean.setHazardList(factory.getMapper(JobsDutiesHazardMapper.class).queryByTid(id));
			// 根据 岗位职责id 查询 岗位职责-职责
			bean.setResponsibilitieList(factory.getMapper(JobsDutiesMapper.class).getResponsibilitiesLibs(id));
		}
		return bean;
	}

	@SuppressWarnings("deprecation")
	public List<JobsDutiesBean> queryList(String name,String corpCode, Integer isleader, Integer start, Integer row){
		List<JobsDutiesBean> list;
		List<String> codeList=new ArrayList<>();
		codeList.add(corpCode);
		try(SessionFactory factory = new SessionFactory();){
			list = factory.getMapper(JobsDutiesMapper.class).list(name,codeList,isleader,start, row);
			if(list.isEmpty()){
				return list;
			}
			List<ResponsibilitiesLibBean> responsibilitiesLibBeans;
			for (JobsDutiesBean bean : list) {
				bean.setTaskList(factory.getMapper(JobsDutiesTaskMapper.class).queryByTid(bean.getId()));
				bean.setCertificateList(factory.getMapper(JobsDutiesCertificateMapper.class).queryByTid(bean.getId()));
				bean.setTrainingList(factory.getMapper(JobsDutiesTrainingMapper.class).queryByTid(bean.getId()));
				bean.setHazardList(factory.getMapper(JobsDutiesHazardMapper.class).queryByTid(bean.getId()));
				// 根据 岗位职责id 查询 岗位职责-职责
				responsibilitiesLibBeans = factory.getMapper(JobsDutiesMapper.class).getResponsibilitiesLibs(bean.getId());
				bean.setResponsibilitieList(responsibilitiesLibBeans);
				StringBuffer sb = new StringBuffer();
				if (responsibilitiesLibBeans != null && responsibilitiesLibBeans.size() > 0){
					for (int i = 0, size = responsibilitiesLibBeans.size(); i < size; i++){
						sb.append((i + 1) + ".");
						if (i == size - 1) {
							sb.append(responsibilitiesLibBeans.get(i).getItem());
						}else {
							sb.append(responsibilitiesLibBeans.get(i).getItem() + "\n");
						}
					}
				}
				bean.setNote(sb.toString());
			}
		}
		return list;

	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	private Map addCheck(JobsDutiesBean bean){
		Map map = new HashMap();
		if(bean == null){
			map.put("code", 35002);
    		map.put("description", "请填写岗位信息");
    		return map;
		}
		if(StringUtils.isEmpty(bean.getCorpCode())){
			map.put("code", 35002);
    		map.put("description", "公司不能为空");
    		return map;
		}
		if(StringUtils.isEmpty(bean.getName())){
			map.put("code", 35002);
    		map.put("description", "岗位名称不能为空");
    		return map;
		}
		if(StringUtils.isEmpty(bean.getNote())){
			map.put("code", 35002);
    		map.put("description", "岗位职责描述不能为空");
    		return map;
		}
		if(bean.getSerial() == null){
			map.put("code", 35002);
    		map.put("description", "排序号不能为空");
    		return map;
		}
		//定人定岗
		List<JobsDutiesTask> taskList = bean.getTaskList();
		int row = 1;
		for (JobsDutiesTask task : taskList) {
			if(StringUtils.isEmpty(task.getTaskTypeId())){
				map.put("code", 35002);
				map.put("description", "定人定岗：行+"+row+"任务类型不能为空");
	    		return map;
			}
			if(StringUtils.isEmpty(task.getTaskObjectId())){
				map.put("code", 35002);
				map.put("description", "定人定岗：行+"+row+"任务对象不能为空");
	    		return map;
			}
			if(StringUtils.isEmpty(task.getNote())){
				map.put("code", 35002);
				map.put("description", "定人定岗：行+"+row+"任务描述不能为空");
	    		return map;
			}
			if(StringUtils.isEmpty(task.getCycleId())){
				map.put("code", 35002);
	    		map.put("description", "定人定岗：行+"+row+"周期不能为空");
	    		return map;
			}
			row++;
		}
		row = 1;
		//证照要求
		List<JobsDutiesCertificate> certificateList = bean.getCertificateList();
		for (JobsDutiesCertificate certificate : certificateList) {
			if(StringUtils.isEmpty(certificate.getCertificateTypeId())){
				map.put("code", 35002);
				map.put("description", "证照要求：行+"+row+"证照名称不能为空");
	    		return map;
			}
			if(StringUtils.isEmpty(certificate.getAuthorization())){
				map.put("code", 35002);
	    		map.put("description", "证照要求：行+"+row+"授权类型不能为空");
	    		return map;
			}
			row++;
		}
		row = 1;
		//培训要求
		List<JobsDutiesTraining> trainingList = bean.getTrainingList();
		for (JobsDutiesTraining training : trainingList) {
			if(StringUtils.isEmpty(training.getTrainingTypeId())){
				map.put("code", 35002);
				map.put("description", "培训要求：行+"+row+"培训类型不能为空");
	    		return map;
			}
			if(StringUtils.isEmpty(training.getCycleId())){
				map.put("code", 35002);
				map.put("description", "培训要求：行+"+row+"培训周期不能为空");
	    		return map;
			}
			if(training.getDuration() == null){
				map.put("code", 35002);
				map.put("description", "培训要求：行+"+row+"培训时长不能为空");
	    		return map;
			}
			row++;
		}
		row = 1;
		//危害因素
		List<JobsDutiesHazard> hazardList = bean.getHazardList();
		for (JobsDutiesHazard hazard : hazardList) {
			if(StringUtils.isEmpty(hazard.getNote())){
				map.put("code", 35002);
				map.put("description", "危害因素：行+"+row+"描述不能为空");
	    		return map;
			}
			row++;
		}
		map.put("code", 0);
		map.put("description", "校验成功");
		return map;
	}

	/**
	 *
	 * @param beanId
	 * @param responsibilitiesLibIds
	 * @param factory
	 */
	private void batchInsertRL(String beanId, String responsibilitiesLibIds, SessionFactory factory) throws Exception {
		try {
			if (!StringUtils.isEmpty(responsibilitiesLibIds)){
				List<String> ids = Splitter.on(",").omitEmptyStrings().trimResults().splitToList(responsibilitiesLibIds);
				List<Map> rls = new LinkedList<>();
				Map map;
				for (String id : ids){
					map = new HashMap();
					map.put("jobsDutiesId", beanId);
					map.put("responsibilitiesLibId", id);
					rls.add(map);
				}
				rls = rls.stream().distinct().collect(Collectors.toList());
				factory.getMapper(JobsDutiesMapper.class).batchInsertRL(rls);
			}
		} catch (Exception e){
			logger.error(e.getMessage(),e);
			throw new Exception(e.getMessage());
		}
	}

	public MessageBean<String> importExcel(StaffBean user, MultipartFile file){
		MessageBean<String> msg=MessageBean.create(BusinessCode.SUCCESS.getCode(),BusinessCode.SUCCESS.getDescription(),String.class);
		try(SessionFactory factory=new SessionFactory()){
			if(null==file){
				msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
				msg.setDescription("未上传文件");
				return msg;
			}
			InputStream inputStream=file.getInputStream();
			XSSFWorkbook workbook=new XSSFWorkbook(inputStream);
			if(null==workbook){
				msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
				msg.setDescription("上传文件为空");
				return msg;
			}
			XSSFSheet sheet=workbook.getSheetAt(0);
			if (null==sheet){
				msg.setCode(BusinessCode.INSUFFICIENT_PARAM.getCode());
				msg.setDescription("上传文件为空");
				return msg;
			}
			List<JobsDuties> dutiesList=new ArrayList<>();
			int rowNumber=sheet.getPhysicalNumberOfRows();
			Date date=new Date();
			int count=factory.getMapper(JobsDutiesMapper.class).count(null,null,null);
			NumberFormat numberFormat = NumberFormat.getNumberInstance();
			numberFormat.setMaximumIntegerDigits(8);//最大位数
			numberFormat.setGroupingUsed(false);
			int temp=0;
			for(int i=1;i<rowNumber;i++){
				XSSFRow row=sheet.getRow(i);
				if(row==null){
					temp++;
					continue;
				}
				String corpName=getCellValue(row.getCell(0));
				String name=getCellValue(row.getCell(1));
				String isLeaderValue=getCellValue(row.getCell(2));
				if(StringUtils.isEmpty(name)||StringUtils.isEmpty(corpName)){
					temp++;
					continue;
				}
				DictData data=dataService.matchDictData("公司",corpName);
				if(null==data){
					temp++;
					continue;
				}
				JobsDuties duties=new JobsDuties();
				int code=count+i-temp;
				duties.setCorpCode(data.getDictValue());
				duties.setCode(numberFormat.format(code));
				duties.setSerial(code);
				duties.setName(name);
				if("是".equals(isLeaderValue)||"Y".equals(isLeaderValue)){
					duties.setIsleader(1);
				}else{
					duties.setIsleader(0);
				}
				duties.setId(DefaultIdGenerator.getInstance().generateLongId());
				duties.setAddTime(date);
				duties.setAddUser(user.getCode());
				duties.setAddUserName(user.getName());
				duties.setUpdateTime(date);
				duties.setUpdateUser(user.getCode());
				duties.setUpdateUserName(user.getName());
				dutiesList.add(duties);
			}
			if(null!=dutiesList&&dutiesList.size()>0){
				factory.getMapper(JobsDutiesMapper.class).batechInsertJobsDuties(dutiesList);
				return msg;
			}else{
				msg.setDescription("文件为空，无法导入数据");
				return msg;
			}
		}catch (Exception e){
			logger.error(e.getMessage(),e);
			msg.setCode(BusinessCode.EXCEPTION.getCode());
			msg.setDescription(BusinessCode.EXCEPTION.getDescription());
			return msg;
		}
	}

	/**
	 * 获取单元格的值
	 * @param cell
	 * @return
	 */
	@SuppressWarnings("deprecation")
	public String getCellValue(XSSFCell cell) {
		if (cell == null)
			return "";
		if (cell.getCellTypeEnum() == CellType.STRING) {
			return cell.getStringCellValue();
		} else if (cell.getCellTypeEnum() == CellType.BOOLEAN) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if (cell.getCellTypeEnum() == CellType.FORMULA) {
			return cell.getCellFormula();
		} else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
			return String.valueOf(cell.getNumericCellValue());
		} else {
			return "";
		}
	}
}
